<template>
  <div class="soundWrap">
    <div :key='item' v-for="(item, key) in vocabulary">
      <audio class="audio" @error="onError" :key='item' :src="item.audio"></audio>
      <div class="soundloading" v-if="soundloading">
        <img src="../static/img/soundloading.png">
      </div>
      <div class="soundplay" v-else @click="startPlay(key, item.audio)" :class="(voice && index === key) ? 'voiceshow' : '' "></div>
    </div>
  </div>
</template>
<script type="text/javascript">
export default {
  data () {
    return {
      soundloading: false,
      voice: false,
      index: null,
      vocabulary:[
          ['audio','http://ztaudio-res.whzcth.com/accompany/none/128/dfa4d7ce-8059-11ea-8aa8-0242ac110004.wav'],
          ['audio','http://ztaudio-res.whzcth.com/accompany/none/128/dfa4d7ce-8059-11ea-8aa8-0242ac110004.wav']
      ]
    }
  },
  methods: {
    // 播放完当前才可播放下一个
    startPlay (key, src) {
      this.index = key
      this.voice = true
      if (!this.currentAudio) {
        this.currentAudio = new Audio(src)
        this.currentAudio.play()
        this.voice = true
        this.currentAudio.onended = () => {
            this.currentAudio = null
            this.voice = false
        }
      }
    },
    // 互斥播放
    startPlay (key, src) {
      let audio = document.querySelectorAll('audio')
      for (var i = 0, len = audio.length; i < len; i++) {
        audio[i].pause()
        this.voice = false
        audio[i].load()
      }
      audio[key].play()
      this.voice = true
      this.index = key
      audio[key].onended = () => {
        this.voice = false
      }
    },
    onError () {
      this.soundloading = true
    },
    // 缓存音频调用
    onWaiting (res) {
      console.log(res)
      this.soundloading = true
    }
  }
}
</script>
<style scoped='scoped' lang="scss">
@keyframes play {
  0% {
    background: url(/static/img/sound1.png) no-repeat;
    background-size: 100% 100%;
  }
  50% {
    background: url(/static/img/sound2.png) no-repeat;
    background-size: 100% 100%;
  }
  100% {
    background: url(/static/img/sound3.png) no-repeat;
    background-size: 100% 100%;
  }
}
.voiceshow {
  animation: play 2s infinite;
  -webkit-animation: play 2s infinite;
}
</style>